<?php

/**
 * Erra_Fields_File - Uploads a file
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_Fields_File extends Erra_Fields_Base_Field {

    public $dir;
    public $isUploaded = false;
    public $allowed_ext = null;

    function __construct($objectId) {
        parent::__construct($objectId);
        $this->setDatabaseType('varchar', 256);
    }

    /**
     * Erra_Fields_File::editInstance() - Shows a browse button with the filename and type if fields already contains data
     *
     * @param mixed $lang
     * @return
     */
    public function editInstance(Array $extraProperties=null) {
        $res = '<div class="erra-form-field-instance">';
        $res .= $this->outputFieldHeader();

        $file = (is_string($this->getRawData())) ? $this->_rawData : '';
        $res .= '<div id="wrapper_file_' . $this->getHtmlId() . '" >
					  <div class="filenamezone">' . $this->getImageDiv() . '</div>';

        if ($this->getRawData() != null) {
            $res .= '<span class="pointer" id="delete_img_' . $this->getHtmlId() . '" rel="' . $this->getHtmlName() . '"><img src="' . config_get("application.http_webroot") . '/__erra/images' . '/cmsimages/del-btn.png"></span>';
        }
        $res .= '<input type="hidden" name="' . $this->getHtmlName() . '" id="' . $this->getHtmlId() . '" value="' . $this->getRawData() . '" />';
        //$res .= '<input name="MAX_FILE_SIZE" value="20971520" type="hidden" />';
        $res .= '<input  name="' . $this->getHtmlId() . '"  id="' . $this->getHtmlId() . '"  type="file" ' . $this->getHtmlAttributes($extraProperties) . ' />';
        $res .= '</div>';
        $res .= '</div>';

        return $res;
    }

    function toHtml($displayParameters = null) {
        return '<div class="' . $this->getClass() . '">' . $this->getRawData() . '</div>';
    }

    /**
     * Erra_Fields_File::getImageDiv() - Returns divs to display image
     *
     * @return
     */
    function getImageDiv() {
        $file = (is_string($this->_rawData)) ? '<a href="' . config_get("application.http_webroot") . '/__files/' . $this->getRawData() . '" target="blank"><b>' . basename($this->_rawData) . '</b></a>' : '';
        $ext = (is_string($this->getRawData())) ? get_file_ext($this->_rawData) : 'x';
        if ($ext) {
            switch (strtolower($ext)) {
                case 'doc': $pos = '0';
                    break;
                case 'bmp': $pos = '16';
                    break;
                case 'jpg': $pos = '32';
                    break;
                case 'jpeg': $pos = '32';
                    break;
                case 'png': $pos = '48';
                    break;
                case 'gif': $pos = '64';
                    break;
                case 'psd': $pos = '80';
                    break;
                case 'mp3': $pos = '96';
                    break;
                case 'wav': $pos = '96';
                    break;
                case 'ogg': $pos = '96';
                    break;
                case 'avi': $pos = '112';
                    break;
                case 'wmv': $pos = '112';
                    break;
                case 'flv': $pos = '112';
                    break;
                case 'pdf': $pos = '128';
                    break;
                case 'exe': $pos = '144';
                    break;
                case 'txt': $pos = '160';
                    break;
                default: $pos = '176';
                    break;
            };

            return '<div style="display:block; background:url(' . config_get("application.http_webroot") . '/__erra/images' . '/filestyle/icons.png) no-repeat 0 -' . $pos . 'px; padding-left:20px;">' . $file . '</div>';
        }
    }

    function getPath() {
        return config_get('path.public_upload_directory') . '/' . $this->getRawData();
    }

    /**
     * Erra_Fields_File::saveUploaded() - The opload method
     *
     * @param mixed $destination
     * @param mixed $ext
     * @param mixed $errMessage
     * @param mixed $optWidth
     * @param mixed $optHeight
     * @param mixed $minWidth
     * @param mixed $minHeight
     * @return
     */
    public function saveUploaded($destination, $ext = null, $errMessage = null, $optWidth = null, $optHeight = null, $minWidth = null, $minHeight = null) {
        if (isset($_FILES[$this->getHtmlId()]) && !empty($_FILES[$this->getHtmlId()]['name'])) {
            $errMessage = (!is_null($errMessage)) ? str_replace('_FILENAME_', $_FILES[$this->getHtmlId()]['name'], $errMessage) : $errMessage;

            if ($_FILES[$this->getHtmlId()]['error']) {
                switch ($_FILES[$this->getHtmlId()]['error']) {
                    case 1: // UPLOAD_ERR_INI_SIZE
                        $this->setMessage("Le fichier dépasse la limite autorisée par le serveur (fichier php.ini) !");

                        return false;

                    case 2: // UPLOAD_ERR_FORM_SIZE
                        $this->setMessage("Le fichier dépasse la limite autorisée dans le formulaire HTML !");

                        return false;

                    case 3: // UPLOAD_ERR_PARTIAL
                        $this->setMessage("L'envoi du fichier a été interrompu pendant le transfert !");

                        return false;

                    case 4: // UPLOAD_ERR_NO_FILE
                        $this->setMessage("Le fichier que vous avez envoyé a une taille nulle !");

                        return false;
                }
            } else {                
                $filename = strip_accents($_FILES[$this->getHtmlId()]['name']);
                $fileExtension = get_file_ext($filename);
                $filename = str_lreplace('.'.$fileExtension, '', $filename);
                $filename .= '-'.uniqid() . '.'.$fileExtension;
                
                $mini_destination = str_replace('_FILENAME_', 'mini-' . $filename, $destination);
                $destination = str_replace('_FILENAME_', $filename, $destination);
                

                if (!is_null($ext)) {
                    $ext = (!is_null($ext)) ? explode('|', $ext) : null;
                    $extIsValid = (!is_null($ext)) ? false : true;
                    $fileExtension = get_file_ext($destination);
                    foreach ($ext as $extension) {
                        $extension = str_replace('.', '', $extension);
                        if (strtolower($extension) == strtolower($fileExtension))
                            $extIsValid = true;
                    }
                    if (!$extIsValid) {
                        $this->setMessage((!is_null($errMessage)) ? $errMessage : 'Le fichier a une extension invalide');

                        return false;
                    }
                }
                $path = dirname($destination);

                if (!is_dir('__files/' . $path)) {
                    mkdir('__files/' . $path, 0777, true);
                }

                move_uploaded_file($_FILES[$this->getHtmlId()]['tmp_name'], '__files/' . $destination);

                $ext = get_file_ext($destination);

                $this->setRawData($destination);

                $this->setMessage(null);
                $this->isUploaded = true;

                return true;
            }
        } else if (!isset($_FILES[$this->getHtmlId()]) && $this->isRequired == true) {
            $this->setMessage(__('Please choose a file'));

            return false;
        }

        $this->setMessage(null);

        return null;
    }

    public function setDir($dir) {
        $this->dir = $dir;
        return $this;
    }

    public function setAllowedExt($allowed) {
        $this->allowed_ext = $allowed;
        return $this;
    }

}

?>